package com.safe.utils;

import com.safe.core.Constant;
import com.safe.exception.ParamErrorException;
import com.safe.service.TrajectoryService;
import org.apache.commons.lang.StringUtils;

/**
 * 点位数据解析
 * Created by tuy on 2020/7/1.
 */
public class PositionUtil {

    @SuppressWarnings("ConstantConditions")
    public static void analysePosition(String content, TrajectoryService trajectoryService) throws ParamErrorException {
        if (StringUtils.isBlank(content)) {
            return;
        }

        String[] result;
        double lon = 0.00;
        double lat = 0.00;
        String direction = "0";
        long time = System.currentTimeMillis();

        for (String str : content.split("[$]")) {
            Integer trainId = 0;

            if (str.contains("GPID")) {
                trainId = Integer.parseInt(str.split(",")[1]);
            }

            if (str.contains("GPGGA")) {
                // 获取时间，位置
                result = str.split(",");

                if (StringUtils.isNotBlank(result[1]))
                    time = DateUtils.stringToLongWithFormat(DateUtils.getDate() + " " + changeTime(result[1]), Constant.TIME_FORMAT_DEFAULT);

                if (StringUtils.isNotBlank(result[4]))
                    lon = changeLon(result[4]);

                if (StringUtils.isNotBlank(result[2]))
                    lat = changeLat(result[2]);
            } else if (str.contains("GPRMC")) {
                // 获取方向
                result = str.split(",");

                if (StringUtils.isNotBlank(result[8]))
                    direction = result[8];
            }

            if (trainId > 0)
                trajectoryService.uploadPosition(trainId, lon, lat, direction, time);
        }
    }

    private static String changeTime(String time) {
        if (StringUtils.isBlank(time))
            return "";

        time = time.substring(0, time.indexOf("."));
        return time.substring(0, 2) + ":" + time.substring(2, 4) + ":" + time.substring(4);
    }

    private static double changeLon(String lon) {
        if (StringUtils.isBlank(lon))
            return 0.00;

        double result = Double.parseDouble(lon.substring(4));
        return Double.parseDouble(lon.substring(0, 3)) + result / 60;
    }

    private static double changeLat(String lat) {
        if (StringUtils.isBlank(lat))
            return 0.00;

        double result = Double.parseDouble(lat.substring(3));
        return Double.parseDouble(lat.substring(0, 2)) + result / 60;
    }
}
